#include "recordmodel.h"
#include <algorithm>

namespace yc {

RecordModel::RecordModel(QObject* parent) : QObject { parent } { }

RecordModel::~RecordModel()
{
    qDeleteAll(records_);
    records_.clear();
}

RecordInfo* RecordModel::record(int id) const
{
    for (RecordInfo* p : std::as_const(records_)) {
        if (p->id == id) {
            return p;
        }
    }
    return nullptr;
}

void RecordModel::add(const RecordInfo& ri)
{
    if (!record(ri.id)) {
        auto p = new RecordInfo { ri };
        records_.push_back(p);
        Q_EMIT added(p, QPrivateSignal());
    }
}

void RecordModel::remove(int id)
{
    auto it = std::find_if(records_.constBegin(), records_.constEnd(),
                           [id](RecordInfo* ri) { return id == ri->id; });
    if (it != records_.constEnd()) {
        Q_EMIT removed(*it, QPrivateSignal());
        delete *it;
        records_.erase(it);
    }
}

void RecordModel::clear()
{
    if (!records_.empty()) {
        Q_EMIT modelAboutToBeReset(QPrivateSignal());
        qDeleteAll(records_);
        records_.clear();
        Q_EMIT modelReset(QPrivateSignal());
    }
}

int RecordModel::presenterCurrentCount(int presenter) const
{
    int count = 0;
    for (RecordInfo* p : std::as_const(records_)) {
        if (p->id == presenter) {
            ++count;
        }
    }
    return count;
}

} // namespace yc
